package com.kgcx.order.service;

import com.github.pagehelper.PageHelper;
import com.kgcx.common.bean.RequestData;
import com.kgcx.common.bean.ReturnData;
import com.kgcx.common.client.coupon.CouponClient;
import com.kgcx.common.client.coupon.pojo.Coupon;
import com.kgcx.common.client.opc.pojo.PriceActualPrice;
import com.kgcx.common.client.organization.DriverClient;
import com.kgcx.common.client.organization.pojo.CustomerMsg;
import com.kgcx.common.client.organization.pojo.Driver;
import com.kgcx.common.client.price.PriceClient;
import com.kgcx.common.eum.OrderEnum;
import com.kgcx.common.rabbitmq.producer.CustomerMsgProducer;
import com.kgcx.common.utils.CollectionUtils;
import com.kgcx.common.utils.date.DateUtils;
import com.kgcx.core.utils.JsonUtil;
import com.kgcx.dbutils.domain.BaseDomain;
import com.kgcx.dbutils.domain.Region;
import com.kgcx.dbutils.utils.CityUtils;
import com.kgcx.dbutils.utils.PageUtils;
import com.kgcx.order.common.MqttListenerUtil;
import com.kgcx.order.common.MqttProducerUtil;
import com.kgcx.order.common.Util;
import com.kgcx.order.domain.Order;
import com.kgcx.order.domain.Order4Flat;
import com.kgcx.order.entity.HotAddress;
import com.kgcx.order.entity.OrderChangeMessage;
import com.kgcx.order.mapper.OrderMapper;
import com.kgcx.order.rabbitmq.OpcProducer;
import com.kgcx.order.vo.DriverPayingOrder;
import com.kgcx.order.vo.UserMileage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Paul on 2017/11/9.
 */
@Service
public class OrderService {

    private static final Logger LOG = LoggerFactory.getLogger(OrderService.class);

    @Autowired
    private OrderMapper mapper;
    @Autowired
    private StringRedisTemplate strRedisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderDriverService orderDriverService;
    @Autowired
    private OrderDriverPaiedService orderDriverPaiedService;
    @Autowired
    private OrderLogService oLogService;
    @Autowired
    private MqttListenerUtil mqttListener;
    @Autowired
    private MqttProducerUtil mqttService;
    @Autowired
    private OpcProducer opcProducer;
    @Autowired
    private DriverClient driverClient;
    @Autowired
    private CustomerMsgProducer customerMsgProducer;
    @Autowired
    private PriceClient priceClient;
    @Autowired
    private CouponClient couponClient;

    public Order getByOrderNo(String orderNo) {
        LOG.info("OrderService.getByOrderNo.orderNo: " + orderNo);
        Order itm = mapper.selectByPrimaryKeyActive(orderNo);
        return itm;
    }

    public Integer getUnpayOrderCount(Long driver_id, Integer time_type) {
        return mapper.getUnpayOrderCount(driver_id, time_type);
    }

    public List<DriverPayingOrder> queryDriverPayingOrder(Long driver_id) {
        List<DriverPayingOrder> ls = mapper.queryDriverPayingOrder(driver_id);
        return ls;

//        Map<String, List<DriverPayingOrder>> result = new HashMap<>();
//
//        for (DriverPayingOrder item: ls)
//        {
//            if(result.keySet().contains(item.getCreate_date()))
//            {
//                result.get(item.getCreate_date()).add(item);
//            }else {
//                List<DriverPayingOrder> list = new ArrayList<>();
//                list.add(item);
//                result.put(item.getCreate_date(), list);
//            }
//        }
//        return result;

    }

    @Transactional(rollbackFor = Exception.class)
    public void update(Order order) {
        LOG.info("OrderService.update.order: " + JsonUtil.toString(order));
        //订单状态从10->12会影响司机代付，所暂时先不将订单状态改为已评价，后面将评价状态从订单状态挪出后再加此处逻辑
        //Panhao Dec 9， 2017
        if (order.getOrderState() != null && order.getOrderState().equals(OrderEnum.COMMENTED)) {
            Order originOrder = getByOrderNo(order.getOrderNo());
            //给乘客发送当前订单状态消息
            OrderChangeMessage mqMsg = new OrderChangeMessage(order.getOrderNo()
                    , OrderEnum.COMMENTED, OrderChangeMessage.MESSAGE_TYPE_COMMENTED, "已评价", order.getPlacingUserId());
            sendMqtt(JsonUtil.toString(mqMsg)
                    , OrderEnum.ORDER_STATE_TOPIC + "." + order.getPlacingUserId());
            if (originOrder.getOrderState().equals(OrderEnum.MARKED_PAIED)) {
                return;
            }
        }
        mapper.updateByPrimaryKeySelective(order);
    }

    public List<Order> list(RequestData requestData, Long driverId, Long userId, Integer state) {
        Order order = new Order();
        if (driverId != null && driverId > 0) {
            order.setDriverId(driverId);
        }
        if (userId != null && userId > 0) {
            order.setPlacingUserId(userId);
        }
        if (state != null && state > 0) {
            order.setOrderState(state);
        }
        PageUtils.page(requestData);
        PageHelper.orderBy("create_time desc");
        return mapper.select(order);
//        return mapper.selectAll();
    }

    @Transactional
    public void add(Order record) {
        try {
            Order order = mapper.selectByPrimaryKeyActive(record.getOrderNo());
            if (order == null) {
                mapper.insertSelective(record);
            }
        } catch (Exception ex) {
            LOG.info(String.format("OrderService.订单持久化add方法：", JsonUtil.toString(record)));
        }
    }

    /**
     * 获取所有进行中的订单（redis）
     *
     * @return
     */
    public List<Order> listIngOrders() {
        Map<Object, Object> ordersMap = strRedisTemplate.opsForHash().entries(OrderEnum.ORDERS_ING);
        List<Order> ls = new ArrayList<>();
        for (Object key : ordersMap.keySet()) {
            //遍历过滤
            Object orderObj = ordersMap.get(key);
            if (orderObj != null) {
                Order order = JsonUtil.toObject(orderObj.toString(), Order.class);
                Order repairOrder = repairOrderState(order);

                //未完成订单不包含orderState=13、14、15、20的订单
                Integer state = repairOrder.getOrderState();
                if (state != 13 && state != 14 && state != 15 && state != 20) {
                    ls.add(repairOrder);
                }

            }

        }

        ls.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));
        return ls;
    }

    /**
     * 获取用户待支付订单列表
     *
     * @return
     */
    public List<Order> listUserPendingPayOrder() {
        List<Order> lsIng = listIngOrders();
        List<Order> lsResult = new ArrayList<>();
        for (Order order : lsIng) {
            if (order.getOrderState().equals(OrderEnum.PENDING_PAY)) {
                lsResult.add(order);
            }
        }
        return lsResult;
    }

    /**
     * 列出司机代付，但是还未支付的订单
     * 改为从数据库获取
     *
     * @param driverId
     * @return
     */
    public List<Order> listDriverPayingOrders(RequestData rqtData, Long driverId) {
//        List<Order> ls = listIngOrders();
//        List<Order> lsResult = new ArrayList<>();
//        for (Order item : ls) {
//            if (item.getDriverId() != null && item.getDriverId().equals(driverId)
//                    && item.getPayType() == OrderEnum.PAY_TYPE_DRIVER
//                    && item.getOrderState() == OrderEnum.MARKED_PAIED) {
//                lsResult.add(item);
//            }
//        }
//
//        return lsResult;
        return list(rqtData, driverId, null, OrderEnum.MARKED_PAIED);
    }

    /**
     * 获取单条正在进行中的订单
     *
     * @param orderNo
     * @return
     */
    public Order getIngOrderByOrderNo(String orderNo) {
        Object obj = strRedisTemplate.opsForHash().get(OrderEnum.ORDERS_ING, orderNo);
        if (obj != null) {
            Order order = JsonUtil.toObject(obj.toString(), Order.class);
            order = repairOrderState(order);
            return order;
        }
        return null;
    }

    /**
     * 根据订单状态表修复主表的订单状态
     *
     * @param order
     * @return
     */
    private Order repairOrderState(Order order) {
        Object obj = strRedisTemplate.opsForHash().get(OrderEnum.ORDERS_STATUS, order.getOrderNo());
        if (obj != null) {
            order.setOrderState(Integer.valueOf(obj.toString().trim()));
        }
        return order;
    }


    public Order getDriverOrdersInService(Long driver_id) {

        if (strRedisTemplate.opsForList().size(Util.getDriverOrdersInServiceKey(driver_id)) > 0) {
            String orderNo = strRedisTemplate.opsForList().index(Util.getDriverOrdersInServiceKey(driver_id), 0);
            Order order = getIngOrderByOrderNo(orderNo);
            return order;
        } else {
            return null;
        }
    }

    //添加
    public void addToDriverOrdersInService(Order order) {
        strRedisTemplate.opsForList().leftPush(Util.getDriverOrdersInServiceKey(order.getDriverId()), order.getOrderNo());
    }

//    public void AddToDriverOrdersPendingPay(Order order) {
//        strRedisTemplate.opsForList().leftPush(Util.getDriverOrdersPendingPayKey(order.getDriverId()), order.getOrderNo());
//    }

    public void addToUserOrdersOngoing(Order order) {
        LOG.info(String.format("OrderService.添加用户进行中订单：", JsonUtil.toString(order)));
        if (OrderEnum.WAIT_ORDER == order.getOrderState()) {
            strRedisTemplate.opsForList().leftPush(Util.getUserOrdersOngoingKey(order.getPlacingUserId()), order.getOrderNo());
        }
    }

    public void addToUserOrdersPendingPay(Order order) {
        strRedisTemplate.opsForSet().add(Util.getUserOrdersPendingPayKey(order.getPlacingUserId()), order.getOrderNo());
    }

    public BigDecimal queryPaiedOrderAmount(Long userId) {
        return mapper.queryPaiedOrderAmount(userId);
    }

    public List<String> queryPaiedOrderList(Long userId) {
        return mapper.queryPaiedOrderList(userId);
    }

    //删除
    public void removeFromDriverOrdersInService(Order order) {
        LOG.info(String.format("OrderService.从司机服务中列表删除订单：{%s}", JsonUtil.toString(order)));
        strRedisTemplate.opsForList().remove(Util.getDriverOrdersInServiceKey(order.getDriverId()), 1, order.getOrderNo());
    }

    //    public void RemoveFromDriverOrdersPendingPay(Order order)
//    {
//        LOG.info(String.format("OrderService.从司机待支付列表删除订单：", JsonUtil.toString(order)));
//        strRedisTemplate.opsForList().remove(Util.getDriverOrdersPendingPayKey(order.getDriverId()), 1, order.getOrderNo());
//    }
    public void removeFromUserOrdersOngoing(Order order) {
        LOG.info(String.format("OrderService.从用户进行中列表删除订单：{%s}", JsonUtil.toString(order)));
        List<String> stringList = strRedisTemplate.opsForList().range(Util.getUserOrdersOngoingKey(order.getPlacingUserId()), 0, -1);
        if (stringList != null && stringList.contains(order.getOrderNo())) {
            LOG.info(String.format("取消立即订单"));
            strRedisTemplate.opsForList().remove(Util.getUserOrdersOngoingKey(order.getPlacingUserId()), 1, order.getOrderNo());
        } else {
            LOG.info(String.format("取消预约订单"));
            strRedisTemplate.opsForList().remove(Util.getUserOrdersPlanOngoingKey(order.getPlacingUserId()), 1, order.getOrderNo());
        }
    }

    public void removeFromUserOrdersPendingPay(Order order) {
        LOG.info(String.format("OrderService.从用户待支付列表删除订单：", JsonUtil.toString(order)));
        strRedisTemplate.opsForSet().remove(Util.getUserOrdersPendingPayKey(order.getPlacingUserId()), order.getOrderNo());
    }

    /**
     * 支付完（包含自己支付和司机标为代付）订单数据持久化
     * 自己支付的话，传入的订单状态应该为11；司机代付的话传入的订单状态应该是10
     *
     * @param order
     */
    @Transactional(rollbackFor = Exception.class)
    public void paiedPersistence(Order order) {
        String orderJson = JsonUtil.toString(order);
        LOG.info(String.format("OrderService.用户支付完成，持久化：{%s}", orderJson));
        if (order != null) {
            LOG.info("OrderService.支付完成.1：订单入库持久化");
            add(order);

            //记录订单变更日志
            LOG.info("OrderService.支付完成.2：记录订单变更日志");
            oLogService.log(order, "订单持久化");

            //redis中删除
            LOG.info("OrderService.支付完成.3：redis中删除");
            strRedisTemplate.opsForHash().delete(OrderEnum.ORDERS_ING, order.getOrderNo());
            strRedisTemplate.opsForHash().delete(OrderEnum.ORDERS_STATUS, order.getOrderNo());

            LOG.info("OrderService.支付完成.4：从用户待支付和司机服务中列表删除");
            if (order.getPlacingUserId() != null && order.getPlacingUserId() > 0) {
                removeFromUserOrdersPendingPay(order);
            }
            if (order.getDriverId() != null && order.getDriverId() > 0) {
                removeFromDriverOrdersInService(order);
            }

            //在给客户推送账单是增加司机营业额
            //LOG.info("OrderService.支付完成.5：增加司机营业额：" + order.getFactPrice());
            //orderDriverService.add(order.getDriverId(), 1, order.getFactPrice(), order.getDepTime());

            if (order.getCouponId() != null) {
                PriceActualPrice priceActualPrice = priceClient.getPriceActualPriceByOrderId(order.getOrderNo());
                if (null != priceActualPrice) {
                    Long totalMoney = priceActualPrice.getTotalMoney();
                    Coupon coupon = couponClient.getCouponInfo(order.getCouponId().longValue());
                    if (null != coupon) {
                        Long trigger = coupon.getTrigger();
                        if (totalMoney >= trigger) {
                            LOG.info(String.format("发送优惠券已使用的MQ消息，订单信息：【%s】。", orderJson));
                            rabbitTemplate.convertAndSend("kgcxOrder", OrderEnum.ROUTING_KEY_ORDER_COUPON_USERD, orderJson);
                        }
                    }

                }

            }
        } else {
            LOG.warn("订单持久化：订单为null");
        }

    }

    /**
     * 司机代付订单状态变更
     *
     * @param order
     */
    @Transactional(rollbackFor = Exception.class)
    public void driverPayUpdate(Order order) {
        String orderJson = JsonUtil.toString(order);
        LOG.info(String.format("OrderService.司机代付支付完成后更新订单状态：{%s}", orderJson));
        if (order != null) {
            order.setOrderState(OrderEnum.PAIED);
            update(order);

            //driver_paied 增加记录
            orderDriverPaiedService.add(order);

        } else {
            LOG.warn("司机代付支付完成后更新订单状态：订单为null");
        }
    }

    /**
     * 取消订单时的持久化
     *
     * @param order
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrderPersistence(Order order) {
        LOG.info(String.format("OrderService.取消订单，持久化：{%s}", JsonUtil.toString(order)));
        try {
            if (order != null) {
                //订单入库
                add(order);

                //记录订单变更日志
                oLogService.log(order, "取消订单 - 订单持久化");

                //redis中删除
                strRedisTemplate.opsForHash().delete(OrderEnum.ORDERS_ING, order.getOrderNo());
                strRedisTemplate.opsForHash().delete(OrderEnum.ORDERS_STATUS, order.getOrderNo());

                //从用户订单列表中删除
                removeFromUserOrdersOngoing(order);
                //如果已派车，则从司机订单列表中也删除
                if (order.getDriverId() != null && order.getDriverId() > 0) {
                    removeFromDriverOrdersInService(order);
                    //司机的订单数减1 //支付完才算接单，所以此处不用减1了
                    //orderDriverService.add(order.getDriverId(), -1, 0);
                }
                //恢复优惠卷状态
                if (null != order.getCouponId()) {
                    couponClient.updateCouponState(order.getCouponId().longValue(), Coupon.STATE_UNUSED);
                }
                //给用户发消息
                CustomerMsg customerMsg = new CustomerMsg();
                customerMsg.setCustomerId(order.getPlacingUserId());
                customerMsg.setTypeId(1);
                customerMsg.setTitle("出行提醒");
                customerMsg.setIsRead(CustomerMsg.UNREAD);
                //您的用车申请（2017-10-10 12:10）已取消，本次取消无任何费用。
                customerMsg.setContent(String.format("您的用车申请（%s）已取消，本次取消无任何费用。", DateUtils.toDateString(order.getCreateTime())));
                customerMsgProducer.customerMsgSend(customerMsg);


            }
        } catch (Exception ex) {
            LOG.info("OrderService.取消订单，异常：", ex);
        }

    }

    public void sendMqtt(String payload, String topic) {
        try {
            LOG.info(String.format("begin send mqtt: payload = 【%s】，topic = 【%s】", payload, topic));
            mqttService.init(topic);
            mqttService.doPublish(1, false, payload, mqttService);
            LOG.info("end send mqtt");
        } catch (Exception ex) {
            LOG.error("send mqtt ex", ex);
        }
    }

    public ReturnData subscribeMqtt(Long id) {
        //订阅消息
        int[] qos = {1};
        String[] topic1 = {OrderEnum.ORDER_STATE_TOPIC + "." + id};
        return mqttListener.subscribeMqttMessage(qos, topic1);

//        System.out.println(gaodeApi.getGaodeRestapi("112.8822040000,28.2315680000,","112.9359300000,27.829250000",5));

    }

//    public List<Order> getIngOrders(Long userId) {
//        //先检索未支付订单
//        List<Order> ls = mapper.selectUnPayOrders4User(userId);
//        if(ls.size()>0){
//            return ls;
//        }else{
//            //没有未支付的话检索进行中订单
//            ls = mapper.selectIngOrders4User(userId);
//            return ls;
//        }
//    }

    /**
     * 分页查询订单数据发送给监管平台
     *
     * @param rd
     * @return
     */
    public List<Order> queryOrderWithPage(RequestData rd) {
        Order order = new Order();
        order.setOrderNo(rd.getString("orderNo"));
        order.setAutoNo(rd.getString("autoNo"));
        order.setDriverName(rd.getString("driverName"));
        order.setDriverPhone(rd.getString("driverPhone"));
        //订单状态
        order.setOrderState(rd.getInteger("orderState"));
        PageUtils.page(rd);
        PageHelper.orderBy(rd.getOrderBy());
        List<Order> list = mapper.selectActive(order);
        for (Order od : list) {
            if (od.getOrderState() == 1) {
                //订单创建
                opcProducer.sendOrderCreate(od);
            } else if (od.getOrderState() == 9) {
                //经营到达
                opcProducer.sendOperateArrived(od);
            } else if (od.getOrderState() == 13) {
                //订单取消
                opcProducer.sendOrderCancel(od);
            }
        }
        return list;
    }

    /**
     * 分页查询订单数据发送给监管平台
     *
     * @param rd
     * @return
     */
    public List<Order> queryBaseOrderWithPage(RequestData rd) {
        Order order = new Order();
        order.setOrderNo(rd.getString("orderNo"));
        order.setAutoNo(rd.getString("autoNo"));
        order.setDriverName(rd.getString("driverName"));
        order.setDriverPhone(rd.getString("driverPhone"));
        //订单状态
        order.setOrderState(rd.getInteger("orderState"));
        PageUtils.page(rd);
        PageHelper.orderBy(rd.getOrderBy());
        List<Order> list = mapper.selectActive(order);
        for (Order od : list) {
            Driver driver = driverClient.getDriver(od.getDriverId(), null);
            Order4Flat of = new Order4Flat();
            of.setOrder(od);
            if (null != driver) {
                of.setDriverLicenseId(driver.getLicenseId());
                of.setAutoNo(driver.getAutoNo());
            }
            if (od.getOrderState() == 3) {
                //订单匹配成功
                opcProducer.sendOrderMatch(of);
            } else if (od.getOrderState() == 4) {
                //经营出发
                opcProducer.sendOperateDepart(of);
            }
        }
        return list;
    }

    public ReturnData getOrderIngList(Map<String, String> paramMap) {
        Map<Object, Object> redisMaps = strRedisTemplate.opsForHash().entries("ORDERS_ING");

        int fromIndex = 0;
        int toIndex = 5;

        if (StringUtils.isNotBlank(paramMap.get("pageNum")) && StringUtils.isNotBlank(paramMap.get("pageSize"))) {
            fromIndex = (Integer.parseInt(paramMap.get("pageNum")) - 1) * Integer.parseInt(paramMap.get("pageSize"));

            toIndex = (Integer.parseInt(paramMap.get("pageNum")) - 1) * Integer.parseInt(paramMap.get("pageSize")) + Integer.parseInt(paramMap.get("pageSize"));
        }

        ArrayList<Map<String, Object>> returnList = redisMaps.values().stream().reduce(new ArrayList<Map<String, Object>>(), (subList, orderJson) -> {
            Map<String, Object> orderMap = JsonUtil.toMap((String) orderJson);
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                Object object = orderMap.get(key);

                if (!key.equals("pageSize") && !key.equals("pageNum")) {
                    if (object == null) {
                        if (StringUtils.isNotEmpty(value)) {
                            return subList;
                        }

                    } else if (!object.toString().contains(value)) {
                        return subList;
                    }
                }
            }

            subList.add(orderMap);
            return subList;
        }, (allList, subList) -> {
            allList.addAll(subList);
            return allList;
        });


        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        ReturnData returnData = new ReturnData();
        returnData.setPageNum(Integer.parseInt(paramMap.get("pageNum") == null ? "0" : paramMap.get("pageNum")));
        returnData.setTotal(returnList.size());


        returnList.sort(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return Long.valueOf(o1.get("createTime").toString()) < Long.valueOf(o2.get("createTime").toString()) ? 1 : -1;
            }
        });

        if (returnList.size() > toIndex) {
            list = returnList.subList(fromIndex, toIndex);


            returnData.setData(list);
            return returnData;
        } else {
            if (returnList.size() > fromIndex) {
                list = returnList.subList(fromIndex, returnList.size());

                returnData.setData(list);
                return returnData;
            } else {
                return new ReturnData<>(new ArrayList<>());
            }
        }

    }


    public List<Order> getFinishOrderList(RequestData rd) {
        rd.remove("ip");
        rd.remove("port");
        if (StringUtils.isNotBlank(rd.getString("createTimeBegin"))) {
            rd.put("createTimeBegin", rd.getTimestamp("createTimeBegin"));
        }
        if (StringUtils.isNotBlank(rd.getString("createTimeEnd"))) {
            rd.put("createTimeEnd", rd.getTimestamp("createTimeEnd"));
        }
        PageUtils.page(rd);
        PageHelper.orderBy(rd.getOrderBy());
        return mapper.selectActive(BaseDomain.buildSelectDomain(rd, new Order()));
    }

    /**
     * 查询所有里程
     *
     * @param userIds
     * @return
     */
    public List<HashMap<Long, Object>> queryUserAllMileage(List<Long> userIds) {
        List<HashMap<Long, Object>> result = mapper.queryUserTotalMileage(userIds);
        LOG.info("全部:" + JsonUtil.toString(result));
        return result;
    }

    /**
     * 查询当月里程
     *
     * @param userIds
     * @return
     */
    public List<HashMap<Long, Object>> queryUserMonthlyMileage(List<Long> userIds) {
        List<HashMap<Long, Object>> result = mapper.queryUserMonthlyMileage(userIds);
        LOG.info("月度：" + JsonUtil.toString(result));

        return result;
    }

    private HashMap<Long, Integer> list2Map(List<HashMap<Long, Object>> ls) {
        HashMap<Long, Integer> result = new HashMap<>();
        for (HashMap<Long, Object> mp : ls) {
            result.put(Long.parseLong(mp.get("key").toString()), Integer.parseInt(mp.get("value").toString()));
        }
        return result;
    }

    /**
     * 查询所有里程
     *
     * @param userIds
     * @return
     */
    public HashMap<Long, UserMileage> queryUserMileage(List<Long> userIds) {
        List<HashMap<Long, Object>> monthly = mapper.queryUserMonthlyMileage(userIds);
        HashMap<Long, Integer> hsMonthly = list2Map(monthly);
        List<HashMap<Long, Object>> total = mapper.queryUserTotalMileage(userIds);
        HashMap<Long, Integer> hsTotal = list2Map(total);

        LOG.info("月度：" + JsonUtil.toString(monthly));
        LOG.info("全部：" + JsonUtil.toString(total));
        HashMap<Long, UserMileage> result = new HashMap<>();
        UserMileage um;
        for (Long key : userIds) {
            um = new UserMileage();
            um.setMonthly(hsMonthly.get(key) == null ? 0 : hsMonthly.get(key));
            um.setTotal(hsTotal.get(key) == null ? 0 : hsTotal.get(key));
            result.put(key, um);
        }
        LOG.info("合集:" + JsonUtil.toString(result));
        return result;
    }

    public List<HotAddress> getHotAddress(Long cityId) {
        return mapper.getHotAddress(cityId);
    }

    public List<Region> getHotCity(Long cityId) {
        List<Long> hotCity = mapper.getHotCity(cityId);
        List<Region> citys = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(hotCity)) {

            for (Long cId : hotCity) {
                citys.add(CityUtils.getCity(cId.intValue()));
            }
        }
        return citys;
    }


}
